package cn.edu.dyxy.service;

import cn.edu.dyxy.dao.OrderDao;
import cn.edu.dyxy.entity.CartItem;
import cn.edu.dyxy.entity.TAddress;
import cn.edu.dyxy.entity.TOrder;
import cn.edu.dyxy.entity.TOrderItem;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author JokerQiu
 * @date 2021年12月25日 15:18
 */

public class OrderService {
    private OrderDao orderDao = new OrderDao();

    public TOrder createOrder(
            TAddress address, Map<String, CartItem> cart, int userId) {
        //创建订单
        TOrder order = new TOrder();
        order.setOrderDesc("您有新的订单了！！！");
        //设置生成订单为当前时间
        order.setOrderTime(System.currentTimeMillis() + "");
        order.setUserId(userId);
        double totalPrice = 0;
        //构建订单详情表
        List<TOrderItem> orderItemList = new ArrayList<>();
        //遍历购物车
        for (CartItem cartItem : cart.values()) {
            TOrderItem orderItem = new TOrderItem();
            orderItem.setAmount(cartItem.getDangPrice() * cartItem.getAmount());
            orderItem.setBookName(cartItem.getBookName());
            orderItem.setDangPrice(cartItem.getDangPrice());
            orderItem.setBookNum(cartItem.getAmount());
            orderItem.setBookId(cartItem.getId());
            totalPrice += orderItem.getAmount();
            orderItemList.add(orderItem);
        }
        order.setTotalPrice(totalPrice);
        //保存订单
        TOrder o = new TOrder();
        try {
            o = orderDao.createOrder(address, order, orderItemList);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return o;
    }
}
